const { defineConfig } = require("@vue/cli-service");
const webpack = require("webpack");

const cliConfig = {
  // 开发环境
  development: {
    configureWebpackDevtool: "eval-cheap-module-source-map", // "eval"
    entry: ["./filename.lint.js", "./src/main.ts"],
  },
  // 测试环境
  test: {
    configureWebpackDevtool: "source-map",
  },
  // 预生产环境
  staging: {
    configureWebpackDevtool: "hidden-source-map",
  },
  // 生产环境
  production: {
    configureWebpackDevtool: false,
    dropConsole: true,
  },
};

module.exports = defineConfig({
  publicPath: process.env.VUE_APP_WEB_BASE_PATH,
  assetsDir: "./static",
  lintOnSave: "warning",
  devServer: {
    port: 8080,
    headers: {
      "Access-Control-Allow-Origin": "*",
    },
    proxy: {
      "^/api": {
        // VUE_APP_DEVELOPMENT_PROXY_IP应为.env.development.local中的参数
        target: process.env.VUE_APP_DEVELOPMENT_PROXY_IP || "http://127.0.0.1:3000",
        changeOrigin: true,
        pathRewrite: {
          "^/api": "",
        },
      },
    },
  },
  configureWebpack: {
    devtool: cliConfig[process.env.NODE_ENV]?.configureWebpackDevtool,
    entry: cliConfig[process.env.NODE_ENV]?.entry,
    plugins: [
      new webpack.ContextReplacementPlugin( // momentjs移除多余的语言包
        /moment[/\\]locale$/,
        /zh-cn/ // 表示只想打包这个正则匹配的文件，正则内容为语言包
      ),
    ],
    optimization: {
      splitChunks: {
        cacheGroups: {
          baseVendors: {
            name: "base-vendors",
            test: /[\\/]node_modules[\\/](vuex|vue-router|axios|mitt|js-cookie)[\\/]/, // 将版本稳定、不受tree shaking影响的依赖打包进来
            minSize: 0,
            minChunks: 1,
            reuseExistingChunk: true,
            chunks: "all",
          },
        },
      },
    },
  },
  chainWebpack(config) {
    // 可通过内联注释手动选定要提前获取的代码：import(/* webpackPrefetch: true */ './AsyncComponent.vue')
    config.plugins.delete("prefetch");
    config.plugins.delete("preload");

    if (cliConfig[process.env.NODE_ENV]?.dropConsole) {
      config.optimization.minimizer("terser").tap((args) => {
        args[0].terserOptions.compress.drop_console = true;
        return args;
      });
    }
  },
  transpileDependencies: [],
});
